package cn.tedu.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.tedu.entity.User;
/**
 * 登录检查过滤器
 * 如果没有登录,就重定向登录页
 * 如果登录就放过
 * @author soft01
 *
 */
public class AccessFilter  implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//转换为子类型		子类方法 API多
		//使用方便
		HttpServletRequest req=(HttpServletRequest)request;
		HttpServletResponse res=(HttpServletResponse)response;
		//检查是否登录
		HttpSession session=req.getSession();
		User user=(User)session.getAttribute("loginUser");
		System.out.println("登录用户:"+user);
		if(user==null) {
			//用户没登录
			System.out.println("用户没有登录");
			String path=req.getContextPath()+"/login.html";
			res.sendRedirect(path);
			return;
		}
		System.out.println("用户已经登录");
		//用户 已经登录成 执行后续的Servlet
		chain.doFilter(req, res);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
